from socket import *
import pymysql


class Dict:
    def __init__(self):
        self.kwargs = {
            "host": "localhost",
            "port": 3306,
            "user": "root",
            "password": "root",
            "database": "dict",
            "charset": "utf8"
        }

        # 数据库连接
        self.db = pymysql.connect(**self.kwargs)
        # 创建游标
        self.cur = self.db.cursor()

    def query_word(self,word):
        sql = "select menu from dict where word = %s"
        self.cur.execute(sql,[word])
        result = self.cur.fetchone()
        if result:
            return result[0]
        else:
            return 'Not Found!'

    def close(self):
        # 关闭
        self.cur.close()
        self.db.close()

class DictServer:
    def __init__(self,host="",port=0):
        self.host = host
        self.port = port
        self.address = (host,port)
        self.dict = Dict()
        self.sock = self._create_socket()

    def _create_socket(self):
        udp_soket = socket(AF_INET,SOCK_DGRAM)
        udp_soket.bind(self.address)
        return udp_soket

    def close(self):
        self.dict.close()
        self.sock.close()

    def start(self):
        while True:
            word,addr = self.sock.recvfrom(1024)
            mean = self.dict.query_word(word.decode())
            self.sock.sendto(mean.encode(),addr)


if __name__ == '__main__':
    server = DictServer(host='0.0.0.0',port=8888)
    server.start()
    server.close()